﻿using System;
using System.Collections.Generic;
using System.Text;

namespace PhotoManager
{
    /// <summary>
    /// Maintains a tree structure to define a partial order among elements
    /// of a particular type T.
    /// </summary>
    public class PartialOrderTree<T>
    {
        Dictionary<T, T> parent = new Dictionary<T, T>();

        /// <summary>
        /// Determines whether a is superior to b under this relation.
        /// </summary>
        /// <param name="a">First element.</param>
        /// <param name="b">Second element.</param>
        /// <returns>true if a is superior to b, false if b is superior to a
        /// or the relation between a and b is undefined.</returns>
        public bool IsSuperior(T a, T b)
        {
            if (a == null)
                throw new ArgumentNullException("a");
            if (b == null)
                throw new ArgumentNullException("b");

            while (true)
            {
                T x;
                if (!parent.TryGetValue(b, out x))
                    return false;
                if (EqualityComparer<T>.Default.Equals(x, a))
                    return true;
                b = x;
            }
        }

        /// <summary>
        /// Gets the partial order between two elements.
        /// </summary>
        /// <param name="a">First element.</param>
        /// <param name="b">Second element.</param>
        /// <returns>Positive if a is superior to b, negative if b is superior
        /// to a, 0 if the order between a and b is not defined.</returns>
        public int GetOrder(T a, T b)
        {
            if (a == null)
                throw new ArgumentNullException("a");
            if (b == null)
                throw new ArgumentNullException("b");

            if (IsSuperior(a, b))
                return 1;
            if (IsSuperior(b, a))
                return -1;
            return 0;
        }

        public bool AddOrder(T a, T b)
        {
            // If the order is already in place, do nothing.
            if (IsSuperior(a, b))
                return true;

            // If the opposite order is in place, we fail.
            if (IsSuperior(b, a))
        }
    }
}
